package com.slipper.common.http;

import java.io.IOException;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.slipper.common.util.GsonUtil;

public class HttpRequestFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(HttpRequestFilter.class);
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpRequestWrapper requestWrapper = new HttpRequestWrapper((HttpServletRequest) servletRequest);
        long startTime = System.currentTimeMillis();
        filterChain.doFilter(requestWrapper, servletResponse);
        try {
            Cookie[] cookies = requestWrapper.getCookies();
            Map<String, String> cookieMap = new HashMap<>();
            if (cookies != null && cookies.length > 0) {
                Arrays.stream(cookies).forEach(cookie -> cookieMap.put(cookie.getName(), cookie.getValue()));
            }
            DecimalFormat df = new DecimalFormat("#0.##");
            logger.info("耗时: {} 秒, url: {}, body: {}, cookie: {}, params: {}, method: {}",
                    df.format((System.currentTimeMillis() - startTime) * 1.0 / 1000),
                    requestWrapper.getRequestURI(),
                    requestWrapper.getBody(),
                    cookieMap,
                    GsonUtil.toJson(requestWrapper.getParameterMap()),
                    requestWrapper.getMethod());
        } catch(Exception e) {
            logger.error("请求参数打印出错！", e);
        }
    }
    
    public Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> headers = new HashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while(enumeration.hasMoreElements()) {
            String header = enumeration.nextElement();
            headers.put(header, request.getHeader(header));
        }
        return headers;
    }
}
